<template>
  <van-popup v-model:show="dialogVisible" position="bottom" :style="{ height: '100%' }" :lock-scroll="false" @closed="handleClose">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="交易中心" left-arrow @click-left="handleClose" />
    
    <!-- 标签切换栏 -->
    <van-tabs v-model:active="activeTab" @change="handleTabChange">
      <van-tab title="我的背包" name="bag">
        <!-- 我的背包内容 -->

        <div class="mobile-bag-container" v-loading="loading">
          <!-- 顶部操作栏 -->
          <div class="mobile-bag-header">
            <!-- 搜索栏 -->
            <div class="search-section">
              <div class="search-wrapper search-container" style="position: relative;">
                <van-search
                  ref="searchInputRef"
                  v-model="searchKeyword"
                  placeholder="搜索物品名称或ID"
                  @update:model-value="handleSearchInputChange"
                  @focus="handleSearchFocus"
                  @clear="handleSearchClear"
                  @compositionstart="handleCompositionStart"
                  @compositionend="handleCompositionEnd"
                >
                  <!-- <template #action>
                    <div @click="handleSearchAction">搜索</div>
                  </template> -->
                </van-search>
                
                <!-- 搜索结果下拉列表 -->
                <div 
                  v-show="showSearchResults" 
                  class="search-dropdown"
                  style="position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ebedf0; border-top: none; border-radius: 0 0 8px 8px; max-height: 200px; overflow-y: auto; z-index: 1000; box-shadow: 0 2px 12px rgba(0,0,0,0.1);"
                >
                  <!-- 加载状态 -->
                  <div v-if="searchLoading || isUserTyping" class="search-loading" style="padding: 12px; text-align: center; color: #969799; font-size: 12px;">
                    <van-loading type="spinner" size="10px" />正在搜索物品...
                  </div>
                  
                  <!-- 无结果状态 -->
                  <div v-else-if="hasSearched && searchResults.length === 0" style="padding: 12px; text-align: center; color: #969799; font-size: 12px;">
                    未找到相关物品
                  </div>
                  
                  <!-- 默认提示 -->
                  <div v-else-if="!hasSearched" style="padding: 12px; text-align: center; color: #969799; font-size: 12px;">
                    请输入物品名称或ID进行搜索
                  </div>
                  
                  <!-- 搜索结果选项 -->
                  <div 
                    v-for="item in searchResults"
                    :key="item.id"
                    @click="selectSearchItem(item)"
                    class="search-result-item"
                    style="padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #f7f8fa; display: flex; justify-content: space-between; align-items: center;"
                  >
                    <span style="color: #323233; font-size: 14px;">{{ item.name }}</span>
                    <span style="color: #969799; font-size: 12px;">ID: {{ item.id }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 视图模式切换 -->
              <van-radio-group v-model="viewMode" direction="horizontal" class="view-mode-radio">
                <van-radio name="compact" class="view-mode-option">紧凑</van-radio>
                <van-radio name="detailed" class="view-mode-option">详细</van-radio>
              </van-radio-group>
            </div>
            
            <!-- 筛选栏 -->
            <div class="filter-section">
              <van-tabs v-model:active="inventoryTypeFilter" @change="handleInventoryTypeChange" type="card">
                <van-tab title="全部" name="all"></van-tab>
                <van-tab title="精灵" name="1"></van-tab>
                <van-tab title="道具" name="2"></van-tab>
                <van-tab title="时装" name="3"></van-tab>
              </van-tabs>
            </div>
          </div>

          <!-- 物品列表 -->
          <div class="mobile-bag-items" ref="bagItemsContainer">
            <div class="mobile-bag-items-scroll" @scroll="handleScroll">
              <van-empty v-if="filteredItems.length === 0 && !loading" description="暂无物品" />

            <van-cell-group>
              <van-cell
                v-for="item in filteredItems"
                :key="item.id + '-' + (item.type === 'pet' ? item.catchTime : 0)"
                class="mobile-bag-item"
                @click="selectItem(item)"
                clickable
              >
                <template #icon>
                  <div class="item-image-wrapper">
                    <!-- 闪光标记 -->
                    <van-icon v-if="item.isShiny" name="star" class="shiny-star" />
                    <van-image :src="item.image" fit="contain" class="item-image" />
                  </div>
                </template>
                
                <template #title>
                  <div class="item-info">
                    <div class="item-header">
                      <div class="item-name">{{ item.name }}</div>
                      <van-tag :type="getTagType(item.type)" size="small" class="item-type-tag">{{ getTypeLabel(item.type) }}</van-tag>
                    </div>
                  </div>
                </template>
                
                <template #label>

                  <!-- 精灵特有属性 - 优化版 -->
                  <div v-if="item.type === 'pet'" class="pet-attributes-optimized">
                    <!-- 基础信息行 -->
                    <div class="pet-basic-info">
                      <van-tag type="success" size="small">Lv.{{ item.level || 0 }}</van-tag>
                      <van-tag :type="getIvTagType(item.iv)" size="small">个体：{{ item.iv || 0 }}</van-tag>
                    </div>
                    
                    <!-- 详细信息（根据视图模式显示） -->
                    <div v-if="viewMode === 'detailed' || expandedItems.has(item.id + '-' + (item.catchTime || 0))" class="pet-details">
                      <div class="pet-evs-grid">
                        <span>攻{{ item.EVAttack || 0 }}</span>
                        <span>防{{ item.EVDefence || 0 }}</span>
                        <span>特攻{{ item.EVSA || 0 }}</span>
                        <span>特防{{ item.EVSD || 0 }}</span>
                        <span>速{{ item.EVSP || 0 }}</span>
                        <span>体{{ item.EVHP || 0 }}</span>
                      </div>
                      <div class="pet-nature-ability-new">
                        <span>{{ item.nature || '未知' }}</span>
                        <span>{{ item.ability === '无特性' ? '--' : item.ability }}</span>
                      </div>
                    </div>
                    
                    <!-- 展开/收起按钮（仅在紧凑模式下显示） -->
                    <van-button 
                      v-if="viewMode === 'compact'" 
                      size="mini" 
                      type="primary" 
                      plain
                      @click.stop="toggleItemDetails(item.id + '-' + (item.catchTime || 0))"
                    >
                      {{ expandedItems.has(item.id + '-' + (item.catchTime || 0)) ? '收起' : '详情' }}
                    </van-button>
                  </div>

                  <!-- 道具数量 -->
                  <div v-if="item.type === 'item'" class="item-quantity">
                    <span>数量: {{ item.maxQuantity || 1 }}</span>
                  </div>
                </template>
              </van-cell>
            </van-cell-group>
        
            <!-- 加载更多提示 -->
            <div v-if="loadingMore" class="loading-more">
              <van-loading type="spinner" size="16px" />加载更多中...
            </div>
            
            <!-- 手动加载更多按钮（调试用） -->
            <div v-if="hasMore && !loadingMore && inventoryItems.length > 0" class="manual-load-more">
              <van-button type="primary" size="small" @click="loadMoreItems" block>
                加载更多
              </van-button>
            </div>
            
            <!-- 没有更多数据提示 -->
            <div v-if="!hasMore && inventoryItems.length > 0" class="no-more">
              <van-icon name="checked" />没有更多物品了
            </div>
            
            <!-- 首次加载提示 -->
            <div v-if="loading && inventoryItems.length === 0" class="initial-loading">
              <van-loading type="spinner" size="20px" />正在加载物品...
            </div>
            </div>
          </div>
        </div>
      </van-tab>

      <!-- 我的上架标签页 -->
      <van-tab title="我的上架" name="listed">
        <div class="mobile-listed-container" v-loading="listedLoading">
          <div class="mobile-listed-scroll">
            <van-empty v-if="myListedItems.length === 0" description="暂无上架物品" />

            <van-cell-group>
            <van-cell
              v-for="item in myListedItems"
              :key="item.listId"
              class="mobile-listed-item"
            >
              <template #icon>
                <van-image :src="item.image" fit="contain" class="listed-item-image" />
              </template>
              
              <template #title>
                <div class="listed-item-header">
                  <span class="listed-item-name">{{ item.name }}</span>
                  <van-tag size="small" :type="getTagType(item.type)" class="item-type-tag">{{ getTypeLabel(item.type) }}</van-tag>
                </div>
              </template>
              
              <template #label>
                <!-- 关键信息行：价格和数量 -->
                <div class="listed-key-info">
                  <div class="price-info">
                    <span class="price-label">价格</span>
                    <span class="price-value">{{ item.price }} XIN豆</span>
                  </div>
                  <div class="quantity-info" v-if="(item.quantity || 1) > 1">
                    <span class="quantity-label">数量</span>
                    <span class="quantity-value">{{ item.quantity || 1 }}</span>
                  </div>
                </div>

                <!-- 底部区域：时间和下架按钮 -->
                <div class="listed-bottom-row">
                  <span class="list-time">{{ formatDate(item.listTime) }}</span>
                  <van-button type="danger" size="small" @click.stop="confirmRemoveItem(item)">
                    下架
                  </van-button>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
          </div>
        </div>
      </van-tab>

      <!-- 交易记录标签页 -->
      <van-tab title="交易记录" name="history">
        <div class="mobile-history-container">
          <!-- 筛选区域 -->
          <div class="history-filters">
            <!-- 快捷筛选按钮 -->
            <div class="quick-filter-buttons">
              <van-button 
                size="small" 
                :type="historyForm.type === 'buy' ? 'primary' : 'default'"
                @click="quickFilterBuy"
                :loading="historyLoading"
              >
                购买记录
              </van-button>
              <van-button 
                size="small" 
                :type="historyForm.type === 'sell' ? 'primary' : 'default'"
                @click="quickFilterSell"
                :loading="historyLoading"
              >
                出售记录
              </van-button>
              <van-button 
                size="small" 
                :type="historyForm.type === '' ? 'primary' : 'default'"
                @click="quickFilterAll"
                :loading="historyLoading"
              >
                全部记录
              </van-button>
            </div>

            <van-cell-group>

              
              <van-field 
                label="开始日期" 
                v-model="historyForm.startDate" 
                readonly 
                is-link 
                @click="showStartDatePicker = true"
              />
              
              <van-field 
                label="结束日期" 
                v-model="historyForm.endDate" 
                readonly 
                is-link 
                @click="showEndDatePicker = true"
              />
            </van-cell-group>

            <div class="filter-actions">
              <van-button type="primary" @click="searchHistory" :loading="historyLoading" block>
                查询
              </van-button>
              <van-button @click="resetHistorySearch" block plain>
                重置
              </van-button>

            </div>
          </div>

          <!-- 交易记录列表 -->
          <div class="history-list">
            <div class="history-list-scroll">
              <van-empty v-if="tradeHistory.length === 0" description="暂无交易记录" />

              <van-cell-group>
              <van-cell v-for="item in tradeHistory" :key="item.id" class="trade-record-card">
                <template #title>
                  <!-- 卡片头部：交易类型、时间和订单号 -->
                  <div class="record-header">
                    <div class="header-left">
                      <van-tag :type="item.type === 'buy' ? 'primary' : 'success'">
                        {{ item.type === 'buy' ? '购买' : '出售' }}
                      </van-tag>
                      <div class="trade-time">{{ formatDateTime(item.time) }}</div>
                    </div>
                    
                    <div class="header-right">
                      <span class="order-number">{{ getShortOrderId(item.orderId) }}</span>
                      <van-button 
                        size="mini" 
                        plain 
                        @click.stop="copyOrderId(item.orderId)" 
                        title="复制完整订单号"
                      >
                        复制
                      </van-button>
                    </div>
                  </div>
                </template>

                <template #value>
                  <!-- 卡片主体：物品信息 -->
                  <div class="record-body">
                    <!-- 物品图片 -->
                    <div class="item-image-wrapper">
                      <van-image :src="item.image" fit="contain" class="item-image" />
                    </div>

                    <!-- 物品详情 -->
                    <div class="item-info">
                      <!-- 精灵类型 -->
                      <template v-if="item.itemType === 'pet'">
                        <!-- 精灵名称 -->
                        <div class="item-title-row">
                          <span class="item-name">{{ item.itemName }}</span>
                          <van-tag size="small" :type="getTagType(item.itemType)" class="item-type-tag">
                            {{ getTypeLabel(item.itemType) }}
                          </van-tag>
                        </div>

                        <!-- 精灵基础信息和属性 -->
                        <div class="pet-attributes-compact" v-if="item.itemDesc !== '数据已过期'">
                          <!-- 基础标签行 -->
                          <div class="pet-basic-tags">
                            <van-tag size="small" type="primary">Lv.{{ getPetLevel(item) }}</van-tag>
                            <van-tag size="small" :type="getIvClass(getPetIv(item))">
                              {{ getPetIv(item) }}
                            </van-tag>
                            <van-tag v-if="isPetShiny(item)" size="small" type="warning">异色</van-tag>
                          </div>
                          
                          <!-- 属性信息行 -->
                          <div class="attributes-line">
                            <span class="attr-group">性格:{{ getPetNature(item) }}</span>
                            <span class="attr-group">特性:{{ getPetAbility(item) }}</span>
                          </div>
                          
                          <!-- 努力值行 -->
                          <div class="stats-line">
                            <span class="stat-item">攻{{ getPetStat(item, 'evAtk') }}</span>
                            <span class="stat-item">特攻{{ getPetStat(item, 'evSa') }}</span>
                            <span class="stat-item">防{{ getPetStat(item, 'evDef') }}</span>
                            <span class="stat-item">特防{{ getPetStat(item, 'evSd') }}</span>
                            <span class="stat-item">速{{ getPetStat(item, 'evSp') }}</span>
                            <span class="stat-item">体{{ getPetStat(item, 'evHp') }}</span>
                          </div>
                        </div>
                      </template>

                      <!-- 道具类型 -->
                      <template v-else>
                        <div class="item-title-row">
                          <span class="item-name">{{ item.itemName }}</span>
                          <van-tag size="small" :type="getTagType(item.itemType)" class="item-type-tag">
                            {{ getTypeLabel(item.itemType) }}
                          </van-tag>
                        </div>
                        <div class="item-quantity" v-if="item.quantity && item.quantity > 1">
                          数量: {{ item.quantity }}
                        </div>
                      </template>
                    </div>

                    <!-- 价格信息 -->
                    <div class="price-section">
                      <div class="total-amount" :class="{ 'expense': item.type === 'buy', 'income': item.type === 'sell' }">
                        <span class="amount-symbol">{{ item.type === 'buy' ? '-' : '+' }}</span>
                        <span class="amount-value">{{ item.price * (item.quantity || 1) }}</span>
                      </div>
                      <div class="currency-label">XIN豆</div>
                    </div>
                  </div>
                </template>
              </van-cell>
              </van-cell-group>
            </div>
          </div>

          <!-- 简单分页控件 -->
          <div v-if="totalPages > 0" class="simple-pagination">
            <van-button 
              size="small"
              :disabled="historyPage <= 1"
              @click="changePage(historyPage - 1)"
            >
              上一页
            </van-button>
            
            <div class="page-info">
              <span class="current-page">{{ historyPage }}</span>
              <span class="page-divider">/</span>
              <span class="total-pages">{{ totalPages }}</span>
            </div>
            
            <van-button 
              size="small"
              :disabled="historyPage >= totalPages"
              @click="changePage(historyPage + 1)"
            >
              下一页
            </van-button>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 交易类型选择器 -->
    <van-popup v-model:show="showTypePicker" position="bottom">
      <van-picker
        :columns="tradeTypeColumns"
        @confirm="onTypeConfirm"
        @cancel="showTypePicker = false"
      />
    </van-popup>

    <!-- 开始日期选择器 -->
    <van-popup v-model:show="showStartDatePicker" position="bottom">
      <van-date-picker
        v-model="tempStartDate"
        title="选择开始日期"
        @confirm="onStartDateConfirm"
        @cancel="showStartDatePicker = false"
      />
    </van-popup>

    <!-- 结束日期选择器 -->
    <van-popup v-model:show="showEndDatePicker" position="bottom">
      <van-date-picker
        v-model="tempEndDate"
        title="选择结束日期"
        @confirm="onEndDateConfirm"
        @cancel="showEndDatePicker = false"
      />
    </van-popup>

    <!-- 底部上架操作区域 -->
    <template v-if="selectedItem && activeTab === 'bag'">
      <div class="mobile-listing-form">
        <div class="selected-item-preview">
          <van-image :src="selectedItem.image" fit="contain" class="preview-image" />
          <div class="preview-name">{{ selectedItem.name }}</div>
        </div>

        <van-form class="listing-form">
          <van-field 
            v-model="listItemForm.price" 
            label="上架价格" 
            type="number" 
            required 
            placeholder="请输入价格"
          />

          <van-field 
            v-if="canSetQuantity"
            v-model="listItemForm.quantity" 
            label="上架数量" 
            type="number" 
            :min="1" 
            :max="selectedItem?.maxQuantity || 1"
            @change="validateQuantity" 
            placeholder="请输入数量"
          />
        </van-form>

        <div class="listing-actions">
          <van-button plain @click="resetForm">取消</van-button>
          <van-button type="primary" @click="confirmList" :loading="listLoading" :disabled="!canSubmit">上架</van-button>
        </div>
      </div>
    </template>
  </van-popup>

  <!-- 二级密码验证对话框 -->
  <van-popup v-model:show="secondaryPasswordVisible" position="center" :close-on-click-overlay="false">
    <div class="secondary-password-container-mobile">
      <van-nav-bar title="安全验证" />
      <div class="verification-content">
        <p class="verification-message">为保障您的账户安全，请输入二级密码进行验证。</p>
        <van-form :model="secondaryPasswordForm" ref="secondaryPasswordFormRef">
          <van-field
            v-model="secondaryPasswordForm.password"
            name="password"
            type="password"
            label="二级密码"
            placeholder="请输入6位数字二级密码"
            maxlength="6"
            :rules="[{ required: true, message: '请输入二级密码' }]"
          />
        </van-form>
        <div class="verification-actions">
          <van-button @click="cancelSecondaryPasswordVerification" block>取消</van-button>
          <van-button type="primary" :loading="verificationLoading" @click="confirmSecondaryPassword" block>
            确认
          </van-button>
        </div>
        <div class="verification-tip">
          <p>如您未设置二级密码，请前往个人资料-账号安全中设置。</p>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, computed, watch, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { showNotify, showDialog } from 'vant'
import 'vant/es/notify/style'
import { getUserItems, sellItem, getMyListingItems, removeListingItem, getTradeRecords } from '@/api/trade'
import { verifySecondaryPassword } from '@/api/user' // 导入二次密码验证API
import { convertItemType, getItemImage, getNatureName, getSpecialAbility } from '@/utils/trade'
import { findItemNameById, findItemsByKeyword } from '@/utils/itemFinder.js'

// 交易记录相关
const historyLoading = ref(false)
const tradeHistory = ref([])
const historyPage = ref(1)
const historyPageSize = ref(10)
const totalPages = ref(0)
const totalItems = ref(0)

const historyForm = reactive({
  type: '',
  typeText: '全部交易类型',
  startDate: '',
  endDate: ''
})

// 交易类型选项
const tradeTypeOptions = [
  { text: '全部交易类型', value: '' },
  { text: '购买', value: 'buy' },
  { text: '出售', value: 'sell' }
]

// van-picker需要的列格式
const tradeTypeColumns = tradeTypeOptions

// 选择器显示状态
const showTypePicker = ref(false)
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 临时日期变量
const tempStartDate = ref(['2024', '01', '01'])
const tempEndDate = ref(['2024', '12', '31'])

// 交易类型变化处理
const onTradeTypeChange = (value) => {
  historyForm.type = value
}

// 交易类型选择确认
const onTypeConfirm = ({ selectedOptions }) => {
  const selectedText = selectedOptions[0]?.text || selectedOptions[0]
  const selectedOption = tradeTypeOptions.find(item => item.text === selectedText)
  if (selectedOption) {
    historyForm.type = selectedOption.value
    historyForm.typeText = selectedOption.text
  }
  showTypePicker.value = false
}

// 开始日期选择确认
const onStartDateConfirm = (date) => {
  const [year, month, day] = date
  historyForm.startDate = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
  showStartDatePicker.value = false
}

// 结束日期选择确认
const onEndDateConfirm = (date) => {
  const [year, month, day] = date
  historyForm.endDate = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
  showEndDatePicker.value = false
}

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 计算需要显示的页码
const displayedPages = computed(() => {
  const pages = []
  const currentPage = historyPage.value
  const maxPages = totalPages.value
  
  // 最多显示5个页码按钮
  let startPage = Math.max(1, currentPage - 2)
  let endPage = Math.min(maxPages, startPage + 4)
  
  if (endPage - startPage < 4) {
    startPage = Math.max(1, endPage - 4)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 加载交易记录 - 修改为使用简单分页
const loadTradeRecords = async () => {
  historyLoading.value = true
  tradeHistory.value = []

  try {
    const params = {
      currentPage: historyPage.value,
      limit: historyPageSize.value
    }

    // 添加交易类型过滤
    if (historyForm.type) {
      params.tradeType = historyForm.type === 'buy' ? 1 : 2
    }

    // 添加时间范围过滤
    if (historyForm.startDate) {
      params.startTime = `${historyForm.startDate} 00:00:00`
    }
    
    if (historyForm.endDate) {
      params.endTime = `${historyForm.endDate} 23:59:59`
    }

    const response = await getTradeRecords(params)

    if (response.code === 200 && response.data) {
      const newRecords = response.data.list.map(item => {
        let itemDesc = null;
        let quantity = 1;

        if (item.itemType === 1) {
          try {
            if (typeof item.itemDesc === 'string') {
              itemDesc = formatPetAttributesToChinese(JSON.parse(item.itemDesc));
            } else if (typeof item.itemDesc === 'object') {
              itemDesc = formatPetAttributesToChinese(item.itemDesc);
            } else if (typeof item.itemDesc === 'undefined') {
              itemDesc = "数据已过期";
            }
          } catch (error) {
            console.error('解析交易记录物品描述失败:', error);
            itemDesc = null;
          }
        } else if (item.itemType === 2) {
          // 对于道具，尝试获取数量
          quantity = item.quantity || 1;
        }

        return {
          id: item.recordId,
          itemId: item.itemId,
          itemName: findItemNameById(item.itemId,item.itemType),
          itemType: convertItemType(item.itemType),
          time: item.create_time,
          type: item.tradeType === 1 ? 'buy' : 'sell',
          price: item.amount,
          quantity: quantity,
          orderId: item.orderId,
          image: getItemImage({
            itemId: item.itemId,
            itemType: item.itemType
          }),
          targetUser: item.account,
          itemDesc: itemDesc
        };
      })

      tradeHistory.value = newRecords
      
      // 设置分页相关数据
      totalItems.value = response.data.total || 0
      totalPages.value = response.data.totalPage || Math.ceil(totalItems.value / historyPageSize.value)
      
      // 如果当前页大于总页数，则返回第一页
      if (historyPage.value > totalPages.value && totalPages.value > 0) {
        historyPage.value = 1
        await loadTradeRecords()
      }
    } else {
      showNotify({ type: 'danger', message: response.msg || '获取交易记录失败' })
    }
  } catch (error) {
    console.error('加载交易记录失败:', error)
    showNotify({ type: 'danger', message: '加载交易记录失败' })
  } finally {
    historyLoading.value = false
  }
}

// 切换页码
const changePage = (page) => {
  historyPage.value = page
  loadTradeRecords()
  // 滚动到页面顶部
  const container = document.querySelector('.mobile-history-container')
  if (container) {
    container.scrollTop = 0
  }
}

// 搜索历史记录
const searchHistory = () => {
  historyPage.value = 1
  loadTradeRecords()
}

// 重置历史搜索
const resetHistorySearch = () => {
  historyForm.type = ''
  historyForm.typeText = '全部交易类型'
  historyForm.startDate = ''
  historyForm.endDate = ''
  historyPage.value = 1
  loadTradeRecords()
}

// 快捷筛选：只显示购买记录
const quickFilterBuy = () => {
  historyForm.type = 'buy'
  historyForm.typeText = '购买'
  historyPage.value = 1
  loadTradeRecords()
}

// 快捷筛选：只显示出售记录
const quickFilterSell = () => {
  historyForm.type = 'sell'
  historyForm.typeText = '出售'
  historyPage.value = 1
  loadTradeRecords()
}

// 快捷筛选：显示全部记录
const quickFilterAll = () => {
  historyForm.type = ''
  historyForm.typeText = '全部交易类型'
  historyPage.value = 1
  loadTradeRecords()
}

// 日期时间格式化函数
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 对话框状态
const props = defineProps({
  showDialog: {
    type: Boolean,
    required: true,
  },
})

const emit = defineEmits(['update:showDialog', 'item-updated'])

const dialogVisible = computed({
  get: () => props.showDialog,
  set: (val) => emit('update:showDialog', val)
})

// 数据和状态
const loading = ref(false)
const listedLoading = ref(false)
const listLoading = ref(false)
const inventoryTypeFilter = ref('all') // 背包物品类型筛选

// 搜索相关变量
const selectedSearchItem = ref(null)
const searchResults = ref([])
const searchLoading = ref(false)
const inventoryItems = ref([])
const selectedItem = ref(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const loadingMore = ref(false)
const refreshing = ref(false) // 下拉刷新状态

// 视图优化相关
const expandedItems = ref(new Set())
const viewMode = ref('compact') // compact | detailed
const listItemForm = ref({
  price: 0,
  quantity: 1
})
const activeTab = ref('bag')
const myListedItems = ref([])

// 二级密码相关
const secondaryPasswordVisible = ref(false);
const secondaryPasswordForm = reactive({
  password: ''
});
const secondaryPasswordFormRef = ref(null);
const verificationLoading = ref(false);
const pendingSellOperation = ref(null); // 用于存储待执行的上架操作
const bagItemsContainer = ref(null); // 背包物品容器引用
const scrollTimer = ref(null); // 滚动防抖定时器

// 滚动处理函数 - 优化版（带防抖和调试）
const handleScroll = (event) => {
  console.log('🔄 滚动事件被触发!', {
    target: event.target.className,
    scrollTop: event.target.scrollTop,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 清除之前的定时器
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value)
  }
  
  // 设置防抖延迟
  scrollTimer.value = setTimeout(() => {
    const { scrollTop, scrollHeight, clientHeight } = event.target
    // 当滚动到底部附近时加载更多，增加防抖和更精确的判断
    const threshold = 50 // 减少阈值，提前50px开始加载
    const isNearBottom = scrollHeight - scrollTop - clientHeight < threshold
    
    // 调试信息（生产环境可以注释掉）
    console.log('📊 滚动数据分析:', {
      scrollTop,
      scrollHeight,
      clientHeight,
      distanceToBottom: scrollHeight - scrollTop - clientHeight,
      threshold,
      isNearBottom,
      hasMore: hasMore.value,
      loadingMore: loadingMore.value,
      itemsLength: inventoryItems.value.length
    })
    
    if (isNearBottom && hasMore.value && !loadingMore.value && inventoryItems.value.length > 0) {
      console.log('🚀 触发加载更多')
      loadMoreItems()
    }
  }, 100) // 100ms防抖延迟
}

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
  resetForm()
  if (tab === 'listed') {
    loadMyListedItems()
  } else if (tab === 'history') {
    // 切换到交易记录标签页时自动加载记录
    historyPage.value = 1
    loadTradeRecords()
  }
}

// 处理标签页切换事件
const handleTabChange = (tabName) => {
  switchTab(tabName)
}

// 过滤后的物品列表
const filteredItems = computed(() => {
  let filtered = [...inventoryItems.value]

  // 类型过滤（搜索功能现在通过下拉框实现，直接在API层面过滤）
  if (inventoryTypeFilter.value !== 'all') {
    const itemType = parseInt(inventoryTypeFilter.value)
    filtered = filtered.filter(item => {
      if (itemType === 1) return item.type === 'pet'
      if (itemType === 2) return item.type === 'item'
      if (itemType === 3) return item.type === 'fashion'
      return true
    })
  }

  return filtered
})

// 是否可以设置数量
const canSetQuantity = computed(() => {
  return selectedItem.value &&
    selectedItem.value.type === 'item' &&
    selectedItem.value.maxQuantity > 1
})

// 是否可以提交
const canSubmit = computed(() => {
  return selectedItem.value &&
    listItemForm.value.price > 15 &&
    listItemForm.value.quantity > 0
})

// 处理背包物品类型筛选变化
const handleInventoryTypeChange = () => {
  // 重置分页
  currentPage.value = 1
  hasMore.value = true
  inventoryItems.value = []
  // 重新加载物品
  loadItems()
}

// 搜索关键词和相关状态
const searchKeyword = ref('')
const showSearchResults = ref(false)
const hasSearched = ref(false)
const isUserTyping = ref(false)
const isComposing = ref(false)
const searchInputRef = ref(null)

// 防抖函数
const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 搜索物品
const searchItems = async (query) => {
  if (!query) {
    searchResults.value = []
    hasSearched.value = false
    searchLoading.value = false
    isUserTyping.value = false
    showSearchResults.value = false
    return
  }
  
  searchLoading.value = true
  
  try {
    // 使用本地 itemFinder 工具进行搜索
    const results = findItemsByKeyword(query)
    // 限制搜索结果数量，避免显示过多结果
    searchResults.value = results.slice(0, 20)
  } catch (error) {
    console.error('搜索物品失败:', error)
    searchResults.value = []
  } finally {
    hasSearched.value = true
    isUserTyping.value = false
    
    // 延迟关闭加载状态
    setTimeout(() => {
      searchLoading.value = false
    }, 200)
  }
}

// 搜索物品 - 使用防抖
const searchItemsDebounced = debounce((query) => {
  searchItems(query)
}, 300)

// 处理搜索输入变化
const handleSearchInputChange = (value) => {
  searchKeyword.value = value
  
  // 如果正在使用中文输入法，不触发搜索
  if (isComposing.value) {
    return
  }
  
  if (!value) {
    showSearchResults.value = false
    searchResults.value = []
    hasSearched.value = false
    isUserTyping.value = false
    searchLoading.value = false
    return
  }
  
  showSearchResults.value = true
  isUserTyping.value = true
  searchItemsDebounced(value)
}

// 搜索框获得焦点
const handleSearchFocus = () => {
  // 如果有输入内容，显示搜索结果
  if (searchKeyword.value) {
    showSearchResults.value = true
  }
}

// 处理搜索按钮点击
const handleSearchAction = () => {
  if (!searchKeyword.value.trim()) {
    handleSearchClear()
    return
  }
  
  // 如果搜索结果只有一个，直接选择它
  if (searchResults.value.length === 1) {
    selectSearchItem(searchResults.value[0])
  } else if (searchResults.value.length > 1) {
    // 多个结果时，选择第一个
    selectSearchItem(searchResults.value[0])
  }
}

// 选择搜索结果项
const selectSearchItem = async (item) => {
  if (!item) return
  
  selectedSearchItem.value = item.id
  searchKeyword.value = `${item.name} (ID: ${item.id})`
  showSearchResults.value = false
  
  try {
    // 重置分页并加载特定物品
    currentPage.value = 1
    hasMore.value = true
    inventoryItems.value = []
    
    // 调用loadItems函数，传入itemId参数来筛选特定物品
    await loadItems(false, item.id)
    showNotify({ type: 'success', message: '成功加载相关物品' })
  } catch (error) {
    console.error('获取物品详情失败:', error)
    showNotify({ type: 'danger', message: '获取物品详情失败' })
  }
}

// 清除搜索
const handleSearchClear = () => {
  searchKeyword.value = ''
  selectedSearchItem.value = null
  searchResults.value = []
  showSearchResults.value = false
  hasSearched.value = false
  isUserTyping.value = false
  searchLoading.value = false
  
  // 重新加载所有物品
  currentPage.value = 1
  hasMore.value = true
  inventoryItems.value = []
  loadItems()
}

// 切换物品详情展开状态
const toggleItemDetails = (itemKey) => {
  if (expandedItems.value.has(itemKey)) {
    expandedItems.value.delete(itemKey)
  } else {
    expandedItems.value.add(itemKey)
  }
}

// 初始加载物品
const loadItems = async (isLoadMore = false, itemId = null) => {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
    currentPage.value = 1
    inventoryItems.value = []
  }
  
  try {
    const params = {
      currentPage: currentPage.value,
      limit: pageSize.value
    }
    
    // 添加类型筛选参数
    if (inventoryTypeFilter.value !== 'all') {
      params.itemType = parseInt(inventoryTypeFilter.value)
    }
    
    // 添加特定物品ID筛选
    if (itemId) {
      params.itemId = itemId
    }
    
    const response = await getUserItems(params)

    if (response.code === 200) {
      const newItems = response.data.map(item => {
        // 根据 item.itemType 判断类型
        const type = convertItemType(item.itemType);
        let petDetails = {};
        if (type === 'pet') {
          petDetails = {
            level: item.level || 0,
            iv: item.dv || 0,
            nature: getNatureName(item.Nature),
            ability: getSpecialAbility(item.special),
            isShiny: item.Shiny === 1,
            evHp: item.EVHP || 0,
            evAtk: item.EVAttack || 0,
            evDef: item.EVDefence || 0,
            evSa: item.EVSA || 0,
            evSd: item.EVSD || 0,
            evSp: item.EVSP || 0,
            addMaxHP: item.addMaxHP || 0,
            catchTime: item.catchTime || 0,
            uuid: item.uuid || 0
          };
        }
        return {
          id: item.itemId,
          name: findItemNameById(item.itemId, item.itemType),
          type: type,
          image: getItemImage(item),
          description: type === 'pet' ? formatPetAttributesToChinese(petDetails) : (item.description || ''),
          maxQuantity: type === 'pet' ? 1 : (item.itemNum || 0),
          catchTime: item.catchTime || 0,
          ...petDetails // 将宠物属性展开到顶层
        };
      })
      
      // 处理分页数据
      if (isLoadMore) {
        // 去重处理，避免重复数据
        const existingIds = new Set(inventoryItems.value.map(item => 
          item.id + '-' + (item.catchTime || 0)
        ))
        const uniqueNewItems = newItems.filter(item => 
          !existingIds.has(item.id + '-' + (item.catchTime || 0))
        )
        inventoryItems.value = [...inventoryItems.value, ...uniqueNewItems]
      } else {
        inventoryItems.value = newItems
      }
      
      // 更新分页状态
      hasMore.value = newItems.length === pageSize.value
      if (hasMore.value && isLoadMore) {
        currentPage.value++
      } else if (!isLoadMore) {
        currentPage.value = 2 // 下次加载第2页
      }
    } else {
      showNotify({ type: 'danger', message: response.msg || '加载背包物品失败' })
    }
  } catch (error) {
    console.error('加载背包物品失败:', error)
    showNotify({ type: 'danger', message: '加载背包物品失败' })
  } finally {
    if (isLoadMore) {
      loadingMore.value = false
    } else {
      loading.value = false
    }
  }
}

// 加载更多物品 - 优化版
const loadMoreItems = async () => {
  if (!hasMore.value || loadingMore.value) return
  
  try {
    // 如果有搜索条件，传递搜索的itemId
    await loadItems(true, selectedSearchItem.value)
  } catch (error) {
    console.error('加载更多物品失败:', error)
    showNotify({ type: 'danger', message: '加载更多物品失败，请重试' })
    // 重置加载状态，允许用户重试
    loadingMore.value = false
  }
}

// 下拉刷新处理函数
const onRefresh = async () => {
  try {
    // 重置分页状态
    currentPage.value = 1
    hasMore.value = true
    inventoryItems.value = []
    
    // 重新加载数据
    await loadItems(false, selectedSearchItem.value)
    
    showNotify({ type: 'success', message: '刷新成功' })
  } catch (error) {
    console.error('刷新失败:', error)
    showNotify({ type: 'danger', message: '刷新失败，请重试' })
  } finally {
    refreshing.value = false
  }
}

// 加载我的上架物品
const loadMyListedItems = async () => {
  listedLoading.value = true
  try {
    const response = await getMyListingItems()

    if (response.code === 200) {
      // 转换接口返回的数据
      myListedItems.value = response.data.map(item => ({
        listId: item.listingId,
        id: item.itemId,
        name: findItemNameById(item.itemId, item.itemType),
        type: convertItemType(item.itemType),
        price: item.unitPrice,
        quantity: item.quantity,
        listTime: item.listTime,
        image: getItemImage(item),
        catchTime: item.itemType === 1 && item.itemDesc ? (JSON.parse(item.itemDesc).catchTime || 0) : 0,
        itemDesc: item.itemType === 1 ? formatPetAttributesToChinese(JSON.parse(item.itemDesc)) : null
      }))

    } else {
      showNotify({ type: 'danger', message: response.msg || '获取我的上架物品失败' })
    }
  } catch (error) {
    console.error('获取我的上架物品列表失败:', error)
    showNotify({ type: 'danger', message: '获取我的上架物品列表失败' })
  } finally {
    listedLoading.value = false
  }
}

// 确认下架物品
const confirmRemoveItem = (item) => {
  showDialog({
    title: '下架确认',
    message: `确定要下架物品 "${item.name}" 吗？`,
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(async () => {
      listedLoading.value = true
      try {
        const response = await removeListingItem({
          listingId: item.listId,
          itemId: item.id,
          removeNum: item.quantity || 1,
          itemType: item.type === 'pet' ? 1 : 2,
          catchTime: item.catchTime
        })

        if (response.code === 200) {
          showNotify({ type: 'success', message: '物品下架成功' })
          // 刷新列表
          await loadMyListedItems()
          emit('item-updated')
        } else {
          showNotify({ type: 'danger', message: response.msg || '下架物品失败' })
        }
      } catch (error) {
        console.error('下架物品失败:', error)
        showNotify({ type: 'danger', message: '下架物品失败' })
      } finally {
        listedLoading.value = false
      }
    })
    .catch(() => {
      // 取消操作，不做任何处理
    })
}

// 选择物品
const selectItem = (item) => {
  selectedItem.value = item
  listItemForm.value.quantity = 1
}

// 重置表单
const resetForm = () => {
  selectedItem.value = null
  listItemForm.value.price = 0
  listItemForm.value.quantity = 1
  // 重置二级密码相关状态
  secondaryPasswordVisible.value = false;
  secondaryPasswordForm.password = '';
  pendingSellOperation.value = null;
  if (secondaryPasswordFormRef.value) {
    secondaryPasswordFormRef.value.resetFields();
  }
}

// 校验数量
const validateQuantity = (value) => {
  if (value > (selectedItem.value?.maxQuantity || 1)) {
    listItemForm.value.quantity = selectedItem.value?.maxQuantity || 1
    showNotify({ type: 'warning', message: `上架数量不能超过当前拥有的数量：${selectedItem.value?.maxQuantity || 1}` })
  }
}

// 封装实际的上架API调用
const executeSellItem = async (params, isFirstAttempt = true) => {
  listLoading.value = true;
  try {
    const response = await sellItem(params);
    if (response.code === 200) {
      showNotify({ type: 'success', message: '物品上架成功' });
      resetForm();
      emit('item-updated'); // 通知父组件更新
      // 如果二级密码弹窗是显示的，关闭它
      if (secondaryPasswordVisible.value) {
        secondaryPasswordVisible.value = false;
        secondaryPasswordForm.password = '';
        pendingSellOperation.value = null;
      }
    } else if (response.code === 9 && isFirstAttempt) {
      // 需要二级密码验证
      pendingSellOperation.value = { data: params };
      secondaryPasswordVisible.value = true;
      showNotify({ type: 'warning', message: '需要二级密码验证' });
    } else {
      showNotify({ type: 'danger', message: response.msg || '上架物品失败' });
    }
  } catch (error) {
    if (error !== 'cancel') { // ElMessageBox.confirm取消时会抛出'cancel'
      console.error('上架物品失败:', error);
      showNotify({ type: 'danger', message: '上架物品失败' });
    }
  } finally {
    listLoading.value = false;
  }
};

// 确认上架
const confirmList = async () => {
  try {
    // 确认信息
    const itemName = selectedItem.value.name;
    const price = listItemForm.value.price;
    const quantity = listItemForm.value.quantity;
    if (price < 15) {
      showNotify({ type: 'danger', message: '价格不能低于15XIN豆' });
      return;
    }
    if (price > 20000000) {
      showNotify({ type: 'danger', message: '价格不能高于20000000XIN豆' });
      return;
    }
    const totalPrice = price * quantity;

    await showDialog({
      title: '上架确认',
      message: `商品: ${itemName}\n单价: ${price} XIN豆\n数量: ${quantity}\n总价: ${totalPrice} XIN豆\n\n成交后将收取5%手续费`,
      confirmButtonText: '确认上架',
      cancelButtonText: '取消'
    })

    // 执行上架
    let itemTypeCode;
    switch (selectedItem.value.type) {
      case 'pet': itemTypeCode = 1; break;
      case 'item': itemTypeCode = 2; break;
      case 'fashion': itemTypeCode = 3; break;
      default: itemTypeCode = 2; // 默认为道具
    }

    const params = {
      itemId: selectedItem.value.id,
      itemType: itemTypeCode,
      sellNum: listItemForm.value.quantity,
      unitPrice: listItemForm.value.price,
      catchTime: selectedItem.value.catchTime
    }
    
    await executeSellItem(params, true); // 调用封装的执行函数

  } catch (error) {
    if (error !== 'cancel') { // ElMessageBox.confirm取消时会抛出'cancel'
      // 此处错误已在 executeSellItem 中处理，或者是指 ElMessageBox 的其他错误
      console.error('上架流程错误:', error);
    }
  }
  // listLoading.value = false; // listLoading 的控制移至 executeSellItem
}


// 确认二级密码
const confirmSecondaryPassword = async () => {
  if (!secondaryPasswordFormRef.value) return;
  
  try {
    // van-form的validate方法返回Promise
    await secondaryPasswordFormRef.value.validate();
    
    if (!/^\d{6}$/.test(secondaryPasswordForm.password)) {
      showNotify({ type: 'danger', message: '二级密码必须是6位数字' });
      return;
    }
    
    verificationLoading.value = true;
    
    try {
      const verifyResponse = await verifySecondaryPassword({ password: secondaryPasswordForm.password });
      if (verifyResponse.code === 200) {
        showNotify({ type: 'success', message: '二级密码验证成功' });
        secondaryPasswordVisible.value = false;
        
        // 如果有待处理的上架操作，重新执行
        if (pendingSellOperation.value) {
          await executeSellItem(pendingSellOperation.value.data, false);
        }
      } else {
        showNotify({ type: 'danger', message: verifyResponse.msg || '二级密码错误' });
      }
    } catch (error) {
      showNotify({ type: 'danger', message: '二级密码验证失败' });
      console.error('二级密码验证错误:', error);
    } finally {
      verificationLoading.value = false;
      secondaryPasswordForm.password = ''; // 清空密码
    }
  } catch (error) {
    // 表单验证失败
    console.error('表单验证失败:', error);
  }
};

const cancelSecondaryPasswordVerification = () => {
  secondaryPasswordVisible.value = false;
  secondaryPasswordForm.password = '';
  pendingSellOperation.value = null; // 用户取消，清除待处理操作
  listLoading.value = false; // 如果之前是loading状态，取消它
};


// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 辅助函数
const getTagType = (type) => {
  switch (type) {
    case 'pet': return 'warning'
    case 'item': return 'success'
    case 'fashion': return 'primary' // 为时装添加一个类型，例如 'primary' 或 'info'
    default: return 'info'
  }
}

const getTypeLabel = (type) => {
  const labels = {
    'pet': '精灵',
    'item': '道具',
    'fashion': '时装' // 添加时装的中文标签
  }
  return labels[type] || '未知'
}

// 获取个体值的CSS类名，添加到script部分
const getIvClass = (iv) => {
  if (!iv) return 'iv-common';

  const ivNum = parseInt(iv);
  if (ivNum >= 30) return 'iv-perfect';
  if (ivNum >= 20) return 'iv-great';
  if (ivNum >= 10) return 'iv-good';
  return 'iv-common';
}

// 获取个体值标签类型
const getIvTagType = (iv) => {
  if (!iv) return 'default';
  
  const ivNum = parseInt(iv);
  if (ivNum >= 30) return 'danger';  // 完美个体值用红色
  if (ivNum >= 20) return 'warning'; // 优秀个体值用橙色
  if (ivNum >= 10) return 'success'; // 良好个体值用绿色
  return 'default'; // 普通个体值用默认色
}

// 格式化宠物属性为中文
const formatPetAttributesToChinese = (petData) => {
  if (!petData) return null;

  return {
    level: petData.level || 0,
    iv: petData.iv || 0,
    nature: petData.nature,
    ability: petData.ability|| '--',
    catchTime: petData.catchTime || 0,
    isShiny: petData.isShiny,
    evAtk: petData.evAtk || 0,
    evSa: petData.evSa || 0,
    evDef: petData.evDef || 0,
    evSd: petData.evSd || 0,
    evHp: petData.evHp || 0,
    evSp: petData.evSp || 0,
    addMaxHP: petData.addMaxHP || 0
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '-';

  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}

// 处理订单号显示和复制
const getShortOrderId = (orderId) => {
  if (!orderId) return '无订单号';
  return orderId.slice(0, 6) + '...';
}

// 复制订单号到剪贴板
const copyOrderId = (orderId) => {
  if (!orderId) {
    showNotify({
      type: 'warning',
      message: '订单号为空，无法复制'
    });
    return;
  }
  
  // 检查浏览器是否支持clipboard API
  if (!navigator.clipboard) {
    // 降级方案：使用传统的复制方法
    try {
      const textArea = document.createElement('textarea');
      textArea.value = orderId;
      textArea.style.position = 'fixed';
      textArea.style.opacity = '0';
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      
      showNotify({
        type: 'success',
        message: '订单号已复制到剪贴板',
        duration: 2000
      });
    } catch (error) {
      console.error('复制失败:', error);
      showNotify({
        type: 'danger', 
        message: '复制失败，请手动复制',
        duration: 3000
      });
    }
    return;
  }
  
  // 使用现代clipboard API
  navigator.clipboard.writeText(orderId)
    .then(() => {
      showNotify({
        type: 'success',
        message: '订单号已复制到剪贴板',
        duration: 2000
      });
    })
    .catch((error) => {
      console.error('复制失败:', error);
      showNotify({
        type: 'danger',
        message: '复制失败，请手动复制',
        duration: 3000
      });
    });
}

// 获取精灵属性的辅助函数
const getPetLevel = (item) => {
  if (!item.itemDesc) return 0;
  return item.itemDesc.level || 0;
}

const getPetIv = (item) => {
  if (!item.itemDesc) return 0;
  return item.itemDesc.iv || 0;
}

const getPetStat = (item, stat) => {
  if (!item.itemDesc) return 0;
  return item.itemDesc[stat] || 0;
}

const getPetNature = (item) => {
  if (!item.itemDesc) return '未知';
  return item.itemDesc.nature || '未知';
}

const getPetAbility = (item) => {
  if (!item.itemDesc) return '--';
  const ability = item.itemDesc.ability;
  return ability === '无特性' ? '--' : (ability || '--');
}

const isPetShiny = (item) => {
  if (!item.itemDesc) return false;
  return item.itemDesc.isShiny;
}

// 监听对话框显示状态
watch(() => dialogVisible.value, (val) => {
  if (val) {
    // 对话框打开时加载数据
    loadItems()
    activeTab.value = 'bag'
    // 确保滚动容器正确初始化
    nextTick(() => {
      initializeScrollContainers()
    })
  } else {
    // 对话框关闭时，也重置二级密码相关状态
    secondaryPasswordVisible.value = false;
    secondaryPasswordForm.password = '';
    pendingSellOperation.value = null;
    verificationLoading.value = false;
    
    // 清除滚动定时器
    if (scrollTimer.value) {
      clearTimeout(scrollTimer.value)
      scrollTimer.value = null
    }
  }
})

// 处理中文输入法开始
const handleCompositionStart = () => {
  isComposing.value = true
}

// 处理中文输入法结束
const handleCompositionEnd = (event) => {
  isComposing.value = false
  // 输入法结束后，触发搜索
  handleSearchInputChange(searchKeyword.value)
}

// 处理点击外部关闭搜索结果
const handleClickOutside = (event) => {
  const searchContainer = event.target.closest('.search-container')
  if (!searchContainer) {
    showSearchResults.value = false
  }
}

// 初始化滚动容器的函数
const initializeScrollContainers = () => {
  const scrollContainers = [
    '.mobile-bag-items-scroll',
    '.mobile-listed-scroll', 
    '.history-list-scroll'
  ]
  
  scrollContainers.forEach(selector => {
    const container = document.querySelector(selector)
    if (container) {
      // 确保容器可以接收触摸事件
      container.style.touchAction = 'pan-y'
      container.style.webkitOverflowScrolling = 'touch'
      container.style.overflowY = 'auto'
      // 强制重新计算滚动区域
      container.scrollTop = container.scrollTop
      // 添加调试信息
      console.log(`初始化滚动容器: ${selector}`, {
        scrollHeight: container.scrollHeight,
        clientHeight: container.clientHeight,
        touchAction: container.style.touchAction,
        overflowY: container.style.overflowY
      })
    }
  })
}

// 组件挂载时添加全局点击事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  
  // 移动端滚动优化：确保滚动容器正确初始化
  nextTick(() => {
    initializeScrollContainers()
  })
})

// 组件卸载时清理定时器和事件监听
onUnmounted(() => {
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value)
  }
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
/* 搜索区域布局 */
.search-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.search-section .van-search {
  flex: 1;
}

/* 视图模式切换样式优化 */
.view-mode-radio {
  flex-shrink: 0;
}

.view-mode-option {
  font-size: 12px !important;
  margin-right: 8px;
}

.view-mode-option :deep(.van-radio__icon) {
  width: 16px !important;
  height: 16px !important;
  font-size: 12px !important;
}

.view-mode-option :deep(.van-radio__label) {
  font-size: 12px !important;
  margin-left: 4px;
}

/* 加载状态样式 */
.loading-more,
.no-more,
.initial-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: #969799;
  font-size: 14px;
  gap: 8px;
}

.loading-more {
  background-color: #f7f8fa;
  border-radius: 8px;
  margin: 8px 12px;
}

.manual-load-more {
  padding: 10px;
  margin: 5px 0;
}

.no-more {
  color: #c8c9cc;
}

.initial-loading {
  padding: 40px 16px;
  color: #1989fa;
}

.el-dialog .el-dialog__body{
  padding: 0px !important;
  height: 100% !important;
}
.mobile-tabs {
  display: flex;
  border-bottom: 1px solid #dcdfe6;
  background: linear-gradient(to right, #1989fa, #5cadff);
  border-radius: 0;
  margin: 0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  font-size: 15px;
  color: rgba(255, 255, 255, 0.8);
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #ffffff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 15%;
  right: 15%;
  height: 2px;
  background-color: #ffffff;
  border-radius: 2px;
}

.mobile-bag-container,
.mobile-listed-container,
.mobile-history-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 92px); /* 减去导航栏(46px)和标签栏(46px)的高度 */
  background-color: #f9fafb;
  overflow: hidden;
  position: relative;
}

/* 移动端全局滚动优化 */
@media (max-width: 768px) {
  .mobile-bag-container,
  .mobile-listed-container,
  .mobile-history-container {
    /* 确保容器在移动端正确处理触摸事件 */
    touch-action: pan-y;
    /* 启用硬件加速 */
    transform: translateZ(0);
    /* 确保容器可以滚动 */
    overflow: hidden;
  }
  
  /* 修复van-popup在移动端的滚动问题 */
  .van-popup {
    touch-action: pan-y;
    /* 确保popup内容可以滚动 */
    overflow: hidden;
  }
  
  /* 确保van-popup的内容区域支持触摸滚动 */
  .van-popup__content {
    touch-action: pan-y;
    overflow: hidden;
    height: 100%;
  }
  
  /* 确保van-pull-refresh不干扰滚动 */
  .van-pull-refresh {
    touch-action: pan-y;
    height: 100%;
    overflow: hidden;
  }
  
  /* 确保van-pull-refresh的内容区域可以滚动 */
  .van-pull-refresh__track {
    height: 100%;
    overflow-y: auto;
  }
}

.mobile-bag-header {
  padding: 8px 10px;
  background-color: #ffffff;
  border-bottom: 1px solid #e6e6e6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 1;
}

.search-bar {
  margin-bottom: 5px;
}

.filter-bar {
  margin-top: 5px;
  display: flex;
  justify-content: center;
}

.view-mode-toggle {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}

.mobile-bag-items {
  flex: 1;
  height: 0; /* 让flex子元素自适应剩余空间 */
  position: relative;
}

.mobile-bag-items-scroll,
.mobile-listed-scroll,
.history-list-scroll {
  height: calc(100vh - 300px);
  overflow-y: auto;
  overflow-x: hidden;
  padding: 5px;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  position: relative;
  /* 确保滚动条可见且可交互 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 transparent;
}

/* 自定义滚动条样式 */
.mobile-bag-items-inner::-webkit-scrollbar {
  width: 6px;
}

.mobile-bag-items-inner::-webkit-scrollbar-track {
  background: transparent;
}

.mobile-bag-items-inner::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.mobile-bag-items-inner::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

/* 移动端触摸滚动优化 */
@media (max-width: 768px) {
  .mobile-bag-items-scroll,
  .mobile-listed-scroll,
  .history-list-scroll {
    /* 强制启用硬件加速 */
    transform: translateZ(0);
    will-change: scroll-position;
    /* 确保触摸滚动流畅 */
    touch-action: pan-y;
    -webkit-overflow-scrolling: touch;
    /* 移动端滚动条通常隐藏 */
    scrollbar-width: none;
    -ms-overflow-style: none;
    /* 确保可以滚动 */
    overflow-y: auto !important;
    overflow-x: hidden !important;
  }
  
  .mobile-bag-items-scroll::-webkit-scrollbar,
  .mobile-listed-scroll::-webkit-scrollbar,
  .history-list-scroll::-webkit-scrollbar {
    display: none;
  }
  
  /* 确保所有子元素不阻止触摸事件 */
  .mobile-bag-items-scroll *,
  .mobile-listed-scroll *,
  .history-list-scroll * {
    touch-action: inherit;
  }
}

.mobile-bag-item {
  display: flex;
  padding: 12px;
  border-radius: 8px;
  background-color: #ffffff;
  margin-bottom: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  position: relative;
  transition: transform 0.2s, box-shadow 0.2s;
}

.mobile-bag-item:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.shiny-star {
  position: absolute;
  top: 3px;
  left: 3px;
  color: #FFD700;
  font-size: 16px;
  filter: drop-shadow(0 0 2px rgba(255, 215, 0, 0.5));
  animation: shine 2s infinite alternate;
}

@keyframes shine {
  from {
    opacity: 0.8;
    transform: scale(0.95);
  }

  to {
    opacity: 1;
    transform: scale(1.05);
  }
}

.item-image {
  width: 45px;
  height: 45px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 6px;
  padding: 4px;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0; /* 防止flex子元素溢出 */
}

.item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 3px;
}

.item-name {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-type-tag {
  flex-shrink: 0; /* 防止标签被压缩 */
}

.item-title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.item-title-row .item-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-type {
  margin-bottom: 4px;
}

.pet-attributes,
.item-quantity {
  margin-top: 5px;
  font-size: 13px;
  color: #606266;
}

.attr-row {
  display: flex;
  gap: 10px;
}

.pet-info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f5f7fa;
  padding: 3px 6px;
  border-radius: 4px;
  min-width: 60px;
}

.info-label {
  font-size: 11px;
  color: #909399;
}

.info-value {
  font-weight: bold;
  color: #303133;
}

.info-value.level {
  color: #67c23a;
}

/* IV值颜色区分 */
.iv-perfect {
  color: #ff4500;
  font-weight: bold;
}

.iv-great {
  color: #e6a23c;
  font-weight: bold;
}

.iv-good {
  color: #67c23a;
}

.iv-common {
  color: #606266;
}

.pet-stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 4px;
  margin-top: 5px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 2px 3px;
  border-radius: 3px;
}

.stat-label {
  font-size: 9px;
  color: #909399;
}

.stat-value {
  font-size: 11px;
  color: #303133;
  font-weight: 500;
}

.mobile-listing-form {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 10px;
  border-top: 1px solid #dcdfe6;
  border-radius: 16px 16px 0 0;
  z-index: 10;
}

.selected-item-preview {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 6px;
}

.preview-image {
  width: 45px;
  height: 45px;
  margin-right: 8px;
}

.preview-name {
  font-weight: bold;
  color: #303133;
}

.listing-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.listing-actions .el-button {
  width: 48%;
  border-radius: 6px;
}

/* 上架物品列表样式 */
.mobile-listed-item {
  display: flex;
  align-items: flex-start;
  padding: 8px;
  border-radius: 8px;
  background-color: #ffffff;
  margin-bottom: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  transition: all 0.2s ease;
}

.mobile-listed-item:active {
  transform: scale(0.98);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.listed-item-image {
  width: 50px;
  height: 50px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 3px;
  flex-shrink: 0;
}

.listed-item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.listed-item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.listed-item-name {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 6px;
}

.listed-key-info {
  display: flex;
  gap: 12px;
  margin-bottom: 4px;
}

.price-info, .quantity-info {
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.price-label, .quantity-label {
  font-size: 10px;
  color: #909399;
  line-height: 1;
}

.price-value {
  font-size: 13px;
  color: #f56c6c;
  font-weight: 600;
  line-height: 1.2;
}

.quantity-value {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  line-height: 1.2;
}

.listed-bottom-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
}

.list-time {
  font-size: 11px;
  color: #c0c4cc;
  flex: 1;
}

.listed-bottom-row .el-button {
  padding: 3px 6px;
  font-size: 11px;
  height: auto;
  min-height: 20px;
  margin-left: 8px;
}

/* 交易记录样式 */
.mobile-history-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 92px);
  background-color: #f9fafb;
  overflow: hidden;
  position: relative;
}

.history-filters {
  padding: 6px 8px;
  background-color: #ffffff;
  border-bottom: 1px solid #e6e6e6;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  z-index: 1;
}

.filter-row {
  margin-bottom: 6px;
}

/* 原生选择框样式 */
.native-select {
  width: 100%;
  height: 34px;
  padding: 0 10px;
  font-size: 13px;
  color: #303133;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23606266' d='M6 8.825L1.175 4 2.05 3.125 6 7.075 9.95 3.125 10.825 4z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 10px center;
  transition: border-color 0.2s;
}

.native-select:focus {
  outline: none;
  border-color: #409eff;
}

/* 日期选择器样式 */
.date-range-container {
  display: flex;
  align-items: center;
  gap: 6px;
}

.native-date {
  flex: 1;
  height: 34px;
  padding: 0 10px;
  font-size: 13px;
  color: #303133;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: border-color 0.2s;
}

.native-date:focus {
  outline: none;
  border-color: #409eff;
}

.date-separator {
  color: #909399;
}

/* 按钮样式 */
.filter-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 6px;
  gap: 6px;
}

.native-button {
  flex: 1;
  height: 34px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background-color: #f5f7fa;
  color: #606266;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.native-button.primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
}

.native-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.native-button:active {
  transform: scale(0.98);
}

/* 分页控件样式 */
.pagination-container {
  margin-top: 8px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 4px;
}

.page-button {
  min-width: 28px;
  height: 28px;
  padding: 0 6px;
  border-radius: 4px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  color: #606266;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.page-button.active {
  background-color: #409eff;
  border-color: #409eff;
  color: #ffffff;
  font-weight: bold;
}

.page-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 13px;
  color: #909399;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 6px;
  height: 0; /* 配合flex: 1 确保正确的滚动行为 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  position: relative;
  /* 确保滚动条可见且可交互 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 transparent;
}

/* 自定义滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track {
  background: transparent;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.history-list::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

/* 移动端触摸滚动优化 */
@media (max-width: 768px) {
  .history-list {
    /* 强制启用硬件加速 */
    transform: translateZ(0);
    will-change: scroll-position;
    /* 确保触摸滚动流畅 */
    touch-action: pan-y;
    /* 移动端滚动条通常隐藏 */
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  
  .history-list::-webkit-scrollbar {
    display: none;
  }
}

.trade-record-card {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  border: 1px solid #f0f0f0;
}

/* 重写van-cell的默认样式 */
.trade-record-card .van-cell {
  padding: 0;
  background-color: transparent;
  border: none;
  display: flex;
  flex-direction: column;
}

.trade-record-card .van-cell__title {
  padding: 0;
  margin: 0;
  flex: none;
}

.trade-record-card .van-cell__value {
  padding: 0;
  margin: 0;
  flex: 1;
  text-align: left;
  min-width: 0;
}

/* 卡片头部样式 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #e9ecef;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.trade-type-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.trade-type-badge.buy {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  color: #1565c0;
  border: 1px solid #90caf9;
}

.trade-type-badge.sell {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  color: #2e7d32;
  border: 1px solid #81c784;
}

.trade-time {
  font-size: 11px;
  color: #666;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 4px;
}

.order-number {
  color: #666;
  font-size: 11px;
  font-family: 'Courier New', monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.copy-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  font-size: 12px;
  border-radius: 4px;
}

.copy-btn:hover {
  color: #409eff;
  background-color: #f0f9ff;
}

/* 卡片主体样式 */
.record-body {
  display: flex;
  padding: 10px 12px;
  gap: 8px;
  align-items: flex-start;
}

.item-image-wrapper {
  width: 40px;
  height: 40px;
  min-width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 6px;
  padding: 3px;
  border: 1px solid #e9ecef;
  flex-shrink: 0;
}

.item-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

/* 物品标题行 */
.item-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
  min-height: 20px;
}

.item-name {
  font-size: 12px;
  font-weight: 600;
  color: #303133;
  flex: 1;
  line-height: 1.4;
  word-break: break-all;
}

.item-type-tag {
  flex-shrink: 0;
}

/* 精灵基础标签 */
.pet-basic-tags {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  margin-bottom: 6px;
  align-items: center;
}

.level-tag {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  color: #2e7d32;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 600;
  border: 1px solid #81c784;
}

.iv-tag {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 600;
  border: 1px solid;
}

/* 精灵属性优化布局 */
.pet-attributes-compact {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.attributes-line {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.attr-group {
  font-size: 12px;
  color: #555;
  background-color: #f8f9fa;
  padding: 4px 8px;
  border-radius: 6px;
  white-space: nowrap;
  border: 1px solid #e9ecef;
  font-weight: 500;
}

.attr-group.shiny {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  color: #e65100;
  border: 1px solid #ffb74d;
  font-weight: 600;
}

.stats-line {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  align-items: center;
}

.stat-item {
  font-size: 11px;
  color: #555;
  background-color: #f0f2f5;
  padding: 3px 6px;
  border-radius: 4px;
  white-space: nowrap;
  border: 1px solid #e1e5e9;
  font-weight: 500;
  min-width: 32px;
  text-align: center;
}

/* 道具数量 */
.item-quantity {
  font-size: 11px;
  color: #666;
  background-color: #f8f9fa;
  padding: 2px 6px;
  border-radius: 4px;
  align-self: flex-start;
}

/* 价格区域 */
.price-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  min-width: 60px;
  flex-shrink: 0;
}

.total-amount {
  display: flex;
  align-items: baseline;
  font-weight: 700;
  font-size: 16px;
  line-height: 1;
}

.total-amount.expense {
  color: #f56c6c;
}

.total-amount.income {
  color: #67c23a;
}

.amount-symbol {
  font-size: 14px;
  margin-right: 2px;
}

.amount-value {
  font-family: 'Courier New', monospace;
}

.currency-label {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
  text-align: right;
}

/* 旧样式已移除，使用新的优化样式 */

.pet-compact-line,
.pet-evs-line,
.pet-nature-ability {
  font-size: 11px;
  margin-bottom: 1px;
  line-height: 1.3;
}

.pet-attributes .pet-compact-line,
.pet-attributes .pet-evs-line,
.pet-attributes .pet-nature-ability {
  background-color: #fafafa;
  padding: 3px 4px;
  border-radius: 3px;
  margin-bottom: 2px;
}

/* 优化后的精灵属性样式 */
.pet-attributes-optimized {
  margin-top: 6px;
}

.pet-basic-info {
  display: flex;
  gap: 4px;
  align-items: center;
  margin-bottom: 4px;
}

/* 优化标签样式 */
.pet-basic-tags .van-tag {
  padding: 4px 8px !important;
  font-size: 11px !important;
  line-height: 1.3 !important;
  border-radius: 6px !important;
  min-width: auto !important;
  white-space: nowrap;
  font-weight: 600 !important;
  border: 1px solid transparent !important;
}

.pet-basic-info .van-tag {
  padding: 1px 4px !important;
  font-size: 10px !important;
  line-height: 1.2 !important;
  border-radius: 3px !important;
  min-width: auto !important;
  white-space: nowrap;
}

/* IV标签特殊样式 */
.pet-basic-info .van-tag:nth-child(2) {
  font-weight: bold;
}

/* 异色标签特殊样式 */
.pet-basic-info .van-tag:last-child {
  padding: 1px 3px !important;
}

.pet-level {
  background: #e1f3d8;
  color: #67c23a;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: bold;
}

.pet-iv {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: bold;
}

.pet-iv.high {
  background: #f0f9ff;
  color: #409eff;
}

.pet-iv.medium {
  background: #fdf6ec;
  color: #e6a23c;
}

.pet-iv.low {
  background: #fef0f0;
  color: #f56c6c;
}

.shiny-badge {
  background: linear-gradient(45deg, #ffd700, #ffed4e);
  color: #8b4513;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: bold;
}

.pet-details {
  background: #fafafa;
  padding: 6px;
  border-radius: 6px;
  margin-bottom: 4px;
}

.pet-evs-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 4px;
  margin-bottom: 4px;
}

.pet-evs-grid span {
  font-size: 10px;
  text-align: center;
  background: white;
  padding: 2px;
  border-radius: 3px;
}

.pet-nature-ability-new {
  display: flex;
  justify-content: space-between;
  font-size: 11px;
  color: #666;
}

.toggle-details {
  background: #f0f2f5;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 10px;
  color: #409eff;
  cursor: pointer;
}

.toggle-details:active {
  background: #e1f3d8;
}

/* 上架物品列表容器 */
.mobile-listed-items {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 5px;
  height: 0; /* 配合flex: 1 确保正确的滚动行为 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
  position: relative;
  /* 确保滚动条可见且可交互 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 transparent;
}

/* 自定义滚动条样式 */
.mobile-listed-items::-webkit-scrollbar {
  width: 6px;
}

.mobile-listed-items::-webkit-scrollbar-track {
  background: transparent;
}

.mobile-listed-items::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.mobile-listed-items::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

/* 移动端触摸滚动优化 */
@media (max-width: 768px) {
  .mobile-listed-items {
    /* 强制启用硬件加速 */
    transform: translateZ(0);
    will-change: scroll-position;
    /* 确保触摸滚动流畅 */
    touch-action: pan-y;
    /* 移动端滚动条通常隐藏 */
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  
  .mobile-listed-items::-webkit-scrollbar {
    display: none;
  }
}

/* 快捷筛选按钮样式 */
.quick-filter-buttons {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 12px;
}

.quick-filter-buttons .van-button {
  flex: 1;
  border-radius: 6px;
  font-size: 13px;
  height: 32px;
  transition: all 0.3s ease;
}

.quick-filter-buttons .van-button--default {
  background-color: #fff;
  border-color: #e4e7ed;
  color: #606266;
}

.quick-filter-buttons .van-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

/* 简单分页控件样式 */
.simple-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin: 15px 0;
  padding-bottom: 5px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  color: #606266;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn:active:not(:disabled) {
  background-color: #e6f1fc;
  border-color: #409eff;
  color: #409eff;
  transform: scale(0.98);
}

.page-info {
  font-size: 13px;
  color: #606266;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 6px 10px;
  border: 1px solid #dcdfe6;
}

.current-page {
  font-weight: bold;
  color: #409eff;
}

.page-divider {
  margin: 0 3px;
  color: #909399;
}

/* 二级密码弹窗特定样式 */
.secondary-password-container-mobile {
  padding: 10px;
}

.secondary-password-container-mobile .verification-message {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  text-align: center;
}

.secondary-password-container-mobile .el-form-item {
  margin-bottom: 20px;
}

.secondary-password-container-mobile .verification-actions {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  margin-top: 20px;
}
.secondary-password-container-mobile .verification-actions .el-button {
  flex-grow: 1;
}

/* 加载更多和没有更多数据的样式 */
.loading-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px;
  color: #909399;
  font-size: 14px;
  gap: 8px;
}

.loading-more .el-icon {
  font-size: 16px;
}

.manual-load-more {
  padding: 10px;
  margin: 10px 0;
}

.no-more {
  color: #c0c4cc;
  font-size: 13px;
}

.secondary-password-container-mobile .verification-tip {
  margin-top: 15px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}
.trade-record-card .van-cell {
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: transparent;
  border: none;
}

.trade-record-card .van-cell__title,
.trade-record-card .van-cell__value {
  padding: 0;
  margin: 0;
  flex: none;
  text-align: left;
}

.trade-record-card.van-cell {
  display: flex;
  flex-direction: column;
}

.trade-record-card .van-cell__value {
  flex: 1;
  min-width: 0;
}
/* 交易记录卡片样式 */
:deep(.trade-record-card.van-cell) {
   display: flex;
   flex-direction: column;
   align-items: stretch;
   padding: 12px;
   margin-bottom: 8px;
   border-radius: 8px;
   overflow: hidden;
   border: 1px solid #f0f0f0;
   background-color: #fff;
}

/* 卡片标题区域 */
:deep(.trade-record-card.van-cell .van-cell__title) {
   padding: 0;
   width: 100%;
}

/* 卡片内容区域 */
:deep(.trade-record-card.van-cell .van-cell__value) {
   padding: 0;
   margin-top: 10px;
   width: 100%;
   color: inherit;
}

.trade-record-card.van-cell {
  display: flex !important;
  flex-direction: column !important;
  align-items: stretch !important;
}

.trade-record-card.van-cell > .van-cell__title,
.trade-record-card.van-cell > .van-cell__value {
  width: 100% !important;
  flex: 1 1 100% !important;
  text-align: left !important;
  padding: 0 !important;
}

.trade-record-card.van-cell > .van-cell__value {
  margin-top: 10px !important;
}
</style>
